<template>
  <div class="hs-tree-wrapper">
    <el-input
      v-model="filterText"
      placeholder="搜索HS编码或名称"
      clearable
      class="filter-input"
    />
    <el-tree-v2
      ref="treeRef"
      :data="treeData"
      :props="defaultProps"
      node-key="code"
      show-checkbox
      highlight-current
      class="hs-tree"
      :expand-on-click-node="false"
      :check-strictly="true"
      @check-change="handleCheckChange"
      :filter-method="onFilter"

    />
  </div>
</template>

<script setup>
import {ref, watch, nextTick, onMounted} from 'vue';
import { treeData as hsTreeData } from '../../utils/ChinahsData.js';

const emit = defineEmits(['selection-change']);
// const props = defineProps({ rawHs: { type: Object, default: () => [] } });

const treeRef = ref(null);
const filterText = ref('');
watch(filterText, (val) => {
  return treeRef.value?.filter(val)
})
const treeData = ref([]);
const rawTree = ref([]);
const defaultProps = { children: 'children', label: 'label',value:'code' };

const nodeMap = new Map();
const parentMap = new Map();

// store selected items as objects
const selectedItems = ref([]);

onMounted(()=>{
  nodeMap.clear(); parentMap.clear();
  function build(nodes, parentCode = null) {
    return Object.values(nodes).reduce((acc, item) => {
      const node = { code: item.code, label: item.label };
      if (item.children) node.children = build(item.children, item.code);
      nodeMap.set(item.code, node);
      parentMap.set(item.code, parentCode);
      acc.push(node);
      return acc;
    }, []);
  }
  // function build(nodes, parentCode = null) {
  //   return Object.values(nodes).map(item => {
  //     const node = { code: item.code, label: item.label, children: item.children ? build(item.children, item.code) : undefined };
  //     nodeMap.set(item.code, node);
  //     parentMap.set(item.code, parentCode);
  //     return node;
  //   });
  // }
  // rawTree.value = build(hsData.hs);
  // treeData.value = rawTree.value;

  rawTree.value =hsTreeData;
  treeData.value = hsTreeData;
})
// function buildTree() {
//   nodeMap.clear(); parentMap.clear();
//   function build(nodes, parentCode = null) {
//     return Object.values(nodes).map(item => {
//       const node = { code: item.code, label: item.label, children: item.children ? build(item.children, item.code) : undefined };
//       nodeMap.set(item.code, node);
//       parentMap.set(item.code, parentCode);
//       return node;
//     });
//   }
//   rawTree.value = build(hsData.rawHs);
//   treeData.value = rawTree.value;
// }

// buildTree();
// watch(() => props.rawHs, buildTree);

function handleCheckChange() {
  const nodes = treeRef.value.getCheckedNodes();
  console.log('当前选中 nodes:', nodes);
  selectedItems.value = nodes.map(n => ({ code: n.code, label: n.label }));
  // console.log('当前选中 items:', selectedItems.value);
  emit('selection-change', selectedItems.value);
}

function onFilter(value,data) {
  if (!value) return true
  return data.label.indexOf(value) !== -1
  // const keyword = filterText.value.trim().toLowerCase();
  // if (!keyword) { treeData.value = rawTree.value; nextTick(() => treeRef.value?.collapseAll()); return; }
  // const matched = [];
  // nodeMap.forEach((node, code) => {
  //   if (node.label.toLowerCase().includes(keyword) || code.toLowerCase().includes(keyword)) matched.push(code);
  // });
  // const visible = new Set();
  // matched.forEach(code => { let cur = code; while (cur) { visible.add(cur); cur = parentMap.get(cur); } });
  // function filterTree(nodes) {
  //   return nodes.filter(n => visible.has(n.code)).map(n => ({ ...n, children: n.children ? filterTree(n.children) : undefined }));
  // }
  // treeData.value = filterTree(rawTree.value);
  // nextTick(() => {
  //   matched.forEach(code => {
  //     let cur = code;
  //     while (cur) {
  //       const node = nodeMap.get(cur);
  //       treeRef.value?.expandNode?.(node);
  //       cur = parentMap.get(cur);
  //     }
  //   });
  // });
}
</script>

<style scoped>
.hs-tree-wrapper { display: flex; flex-direction: column; }
.filter-input { margin-bottom: 12px; width: 100%; }
.hs-tree { flex: 1; max-height: 600px; overflow: auto; border: 1px solid #ebeef5; padding: 10px; }
</style>
